package edu.towson.android.graphgrammar.util;

import java.io.File;
import java.io.IOException;

import edu.towson.android.graphgrammar.IConstants;

public class FileUtil {

	public static boolean isValidExistingDirectory(String fullPathName) {
		if (fullPathName == null || fullPathName.isEmpty()) {
			return false;
		}
		fullPathName = fullPathName.trim();
		File dir = new File(fullPathName);
		if (!dir.exists()) {
			return false;
		}
		if (!dir.isDirectory()) {
			return false;
		}
		return true;
	}

	public static File getExistingFileFromDirGivenFileName(
			String fullPathDirName, String fileName) throws IOException {
		if (fullPathDirName == null || fullPathDirName.isEmpty()) {
			throw new IllegalArgumentException(
					"The fullPathDirName must be provided");
		}
		if (fileName == null || fileName.isEmpty()) {
			throw new IllegalArgumentException("The fileName must be provided");
		}

		fullPathDirName = fullPathDirName.trim();
		fileName = fileName.trim();
		if (!isValidExistingDirectory(fullPathDirName)) {
			throw new IOException("The fullPathDirName:" + fullPathDirName
					+ " is not valid!");
		}

		if (!fileName.contains(fullPathDirName)) {
			if (!fullPathDirName.endsWith(IConstants.FILE_SEPARATOR)) {
				fullPathDirName = fullPathDirName + IConstants.FILE_SEPARATOR;
			}
			fileName = fullPathDirName + fileName;
		}

		File file = new File(fileName);
		if (!file.exists()) {
			throw new IOException("The file :" + fileName
					+ " does not exist in the dir:" + fullPathDirName);
		}
		return file;
	}

}
